<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="visible"
    :before-close="cancel"
    lock-scroll
    :append-to-body="true"
    style="margin: 20px 40px;"
    fullscreen
  >
    <el-form
      class="edit-form"
      status-icon
      :model="datas"
      :rules="rules"
      @keyup.enter.native="save"
      ref="editForm"
    >
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item prop="project_id" label="项目名称" :label-width="baseStyle.width">
            <el-select
              v-model="datas.project_id"
              placeholder="请选择"
              style="width: 100%;"
              @change="changeClassic"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id+item.project_name"
                :label="item.project_name"
                :value="item.id"
                :disabled="!isAdd?true:false"
              ></el-option>
            </el-select>
            <!-- <el-input v-model="formData.name" :readonly="true" autocomplete="off"></el-input> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="project_no" label="项目编号" :label-width="baseStyle.width">
            <el-input v-model="datas.project_no" :readonly="true" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="class_name" label="项目类别" :label-width="baseStyle.width">
            <el-input v-model="datas.class_name" :readonly="true" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            prop="currentStage"
            :label="`${stageData.name?'项目阶段（'+stageData.name+'）':'项目阶段'}`"
            :label-width="baseStyle.width"
          >
            <el-date-picker
              v-if="stageData.id&&stageData.name"
              v-model="stageData.value"
              :readonly="true"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
            <div v-else>暂无</div>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="!isAdd">
          <el-form-item prop="curr_moth_plan" label="本月计划" :label-width="baseStyle.width">
            <el-input
              :readonly="true"
              type="textarea"
              autocomplete="off"
              placeholder="暂无计划"
              v-model="datas.curr_moth_plan"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="project_desc" label="项目概述" :label-width="baseStyle.width">
            <el-input
              type="textarea"
              autocomplete="off"
              placeholder="请填写"
              v-model="datas.project_desc"
            />
          </el-form-item>
        </el-col>
        <div v-for="(item,index) in weekPLan" :key="item.propName+index">
          <el-col :span="24">
            <el-form-item
              :prop="item.propName"
              :label="`${index==0?'本周工作及完成率':''}`"
              :label-width="baseStyle.width"
              :rules="{
                validator: (rule, value, callback)=>{
                  validWeek(rule, value, callback,weekPLan);
                  callback();
                }, trigger: 'blur'
              }"
            >
              <el-input
                type="textarea"
                autocomplete="off"
                placeholder="请输入工作内容"
                v-model="item.content"
                :readonly="item.readonly?true:false"
                rows="2"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :prop="item.propRate" :label-width="baseStyle.width">
              <el-slider style="margin-left:20px" v-model="item.percentage" show-input></el-slider>
            </el-form-item>
          </el-col>
          <el-col v-if="(index+1)==weekPLan.length" :span="12" style="text-align:center">
            <el-button type="primary" size="small" @click="addMoreWeekPlan">增加</el-button>
            <el-button type="primary" size="small" @click="delMoreWeekPlan">删除</el-button>
          </el-col>
        </div>
        <div v-for="(item,index) in nextWeekPLan" :key="item.propName+index">
          <el-col :span="24">
            <el-form-item
              :prop="item.propName"
              :label="`${index==0?'下周工作及完成率':''}`"
              :label-width="baseStyle.width"
              :rules="{
                validator: (rule, value, callback)=>{
                  validWeek(rule, value, callback,nextWeekPLan);
                  callback();
                }, trigger: 'blur'
              }"
            >
              <el-input
                type="textarea"
                autocomplete="off"
                placeholder="请输入工作内容"
                v-model="item.content"
                rows="2"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :prop="item.propRate" :label-width="baseStyle.width">
              <el-slider style="margin-left:20px" v-model="item.percentage" show-input></el-slider>
            </el-form-item>
          </el-col>
          <el-col v-if="(index+1)==nextWeekPLan.length" :span="12" style="text-align:center">
            <el-button type="primary" size="small" @click="addMoreNextWeekPlan">增加</el-button>
            <el-button type="primary" size="small" @click="delMoreNextWeekPlan">删除</el-button>
          </el-col>
        </div>
        <el-col :span="24">
          <el-form-item prop="main_content" label="重大问题及风险" :label-width="baseStyle.width">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="datas.main_content"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button :type="'primary'" @click.native="save">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { Message } from "element-ui";
import projectAPI from "@apis/newProject";
import workAPI from "@apis/work";
export default {
  name: "editForm",
  props: {
    title: String,
    baseStyle: Object,
    datas: {
      type: Object,
      default: {}
    },
    visible: Boolean,
    isAdd: Boolean,
    saveForm: Function,
    uid: Number
  },
  data() {
    const rules = this.getRules();

    return {
      rules,
      //innerdialog参数
      innerVisible: false,
      projectList: [],
      currentStage: "",
      weekPLan: [
        {
          propName: "weekDescri1",
          content: "",
          propRate: "weekRate1",
          percentage: 0
        }
      ],
      nextWeekPLan: [
        {
          propName: "nextWeekDescri1",
          content: "",
          propRate: "nextWeekRate1",
          percentage: 0
        }
      ],
      stageData: { id: null, name: "", value: [] }
    };
  },
  components: {},
  computed: {},
  created() {
    this.getProjectList({ uid: this.uid });
    if (!this.isAdd) {
      this.formWorkData();
      this.getStageCurr({
        class: this.datas.class_id,
        id: this.datas.project_id
      });
    } else {
      this.datas.workcontent = [];
    }
  },
  methods: {
    //初始化work的数据还有nextwork数据
    formWorkData() {
      if (this.datas.workcontent && this.datas.workcontent.length > 0) {
        this.weekPLan = [];
        this.datas.workcontent.map((item, index) => {
          this.weekPLan.push({
            propName: `weekDescri${index + 1}`,
            content: item.content,
            readonly: true,
            propRate: `weekRate${index + 1}`,
            percentage: item.percentage * 1
          });
        });
      } else {
        this.datas.workcontent = [];
      }
      if (this.datas.workplan && this.datas.workplan.length > 0) {
        this.nextWeekPLan = [];
        this.datas.workplan.map((item, index) => {
          this.nextWeekPLan.push({
            propName: `nextWeekDescri${index + 1}`,
            content: item.next_content,
            propRate: `nextWeekRate${index + 1}`,
            percentage: item.next_percentage * 1
          });
        });
      }
    },
    //立项申请的项目类别下拉框数据getPLanList
    getProjectList(data) {
      projectAPI
        .getProjectLists(data)
        .then(res => {
          this.projectList = [...res];
          if (this.datas && this.datas.project_id) {
            let curItem = res.filter(item => this.datas.project_id === item.id);
            this.datas.project_no = curItem[0].project_no;
            this.datas.class_name = curItem[0].class_name;
            this.datas.class_id = curItem[0].project_class;
          }
        })
        .catch(err => this.$message.error(err.message));
    },
    //根据类别获取当前阶段
    getStageCurr(val) {
      projectAPI
        .getStageCurrInfo(val)
        .then(res => {
          if (res && res.id) {
            this.stageData.id = res.id;
            this.stageData.name = res.name;
            this.stageData.value = [res.start_time, res.end_time];
          }
        })
        .catch(err => {
          this.stageData = { id: null, name: "", value: [] };
          if (!err.message == "获取失败！") {
            this.$message.error(err.message);
          }
        });
    },
    //选择classic时联动stage
    changeClassic(val) {
      let curItem = this.projectList.filter(item => val === item.id);
      this.getStageCurr({
        class: curItem[0].project_class,
        id: curItem[0].id
      });
      // console.log(curItem, "curItem");
      this.datas.project_no = curItem[0].project_no;
      this.datas.class_name = curItem[0].class_name;
      this.datas.class_id = curItem[0].project_class;
      this.getWeekPlans({ uid: this.uid, project_id: curItem[0].id });
    },
    //根据选择项目填充本周工作计划（即上周填写的下周工作计划）
    getWeekPlans(val) {
      workAPI
        .weekPLanCount(val)
        .then(res => {
          // console.log(res);
          if (res.workplan && res.workplan.length > 0) {
            this.datas.workcontent = [...res.workplan];
            this.weekPLan = [];
            this.datas.workcontent.map((item, index) => {
              this.weekPLan.push({
                propName: `weekDescri${index + 1}`,
                content: item.next_content,
                readonly: true,
                propRate: `weekRate${index + 1}`,
                percentage: item.next_percentage * 1
              });
            });
          } else {
            this.datas.workcontent = [];
            this.weekPLan = [
              {
                propName: "weekDescri1",
                content: "",
                propRate: "weekRate1",
                percentage: 0
              }
            ];
          }
        })
        .catch(err => {
          // console.log(err, "err");
          if (err.message == "获取失败！") {
            this.datas.workcontent = [];
            this.weekPLan = [
              {
                propName: "weekDescri1",
                content: "",
                propRate: "weekRate1",
                percentage: 0
              }
            ];
            return;
          }
          this.$message.error(err.message);
        });
    },
    addMoreWeekPlan() {
      if (!this.datas.project_id) {
        this.$message.warning("请先选择项目");
        return;
      }
      let len = this.weekPLan.length + 1;
      this.weekPLan.push({
        propName: `weekDescri${len}`,
        content: "",
        propRate: `weekRate${len}`,
        percentage: 0
      });
    },
    delMoreWeekPlan() {
      let len = this.weekPLan.length;
      if (len === 1 && !this.datas.id && this.datas.workcontent.length < 1) {
        this.$message.warning("至少有一组");
        return;
      }
      if (
        (this.datas.id || this.datas.project_id) &&
        len === this.datas.workcontent.length
      ) {
        this.$message.warning("已有数据不能删除");
        return;
      }
      // if (this.datas.id && len === this.datas.workcontent.length) {
      //   this.$message.warning("已有数据不能删除");
      //   return;
      // }
      this.weekPLan = this.weekPLan.filter((item, index) => index + 1 !== len);
    },
    addMoreNextWeekPlan() {
      if (!this.datas.project_id) {
        this.$message.warning("请先选择项目");
        return;
      }
      let len = this.nextWeekPLan.length + 1;
      this.nextWeekPLan.push({
        propName: `nextWeekDescri${len}`,
        content: "",
        propRate: `nextWeekRate${len}`,
        percentage: 0
      });
    },
    delMoreNextWeekPlan() {
      let len = this.nextWeekPLan.length;
      if (len === 1 && !this.datas.id) {
        this.$message.warning("至少有一组");
        return;
      }
      if (this.datas.id && len === this.datas.workplan.length) {
        this.$message.warning("已有数据不能删除");
        return;
      }
      this.nextWeekPLan = this.nextWeekPLan.filter(
        (item, index) => index + 1 !== len
      );
    },
    cancel() {
      this.$emit("update:visible", false);
      this.$emit("update:datas", {});
      this.$refs.editForm.resetFields();
    },
    formSaveData(data, week) {
      let newArr = [];
      data.map(item => {
        let newObj = {};
        if (!item.content) {
          return this.$refs.editForm.validateField(`${item.propName}`);
        }
        week
          ? newArr.push({
              content: item.content,
              percentage: item.percentage
            })
          : newArr.push({
              next_content: item.content,
              next_percentage: item.percentage
            });
      });
      return newArr;
    },
    save() {
      let formData = {};
      formData.workcontent = [...this.formSaveData(this.weekPLan, true)];
      formData.workplan = [...this.formSaveData(this.nextWeekPLan, false)];
      this.$refs.editForm.validate(valid => {
        if (valid) {
          formData.project_id = this.datas.project_id;
          formData.project_desc = this.datas.project_desc
            ? this.datas.project_desc
            : "";
          formData.class_id = this.datas.class_id;
          formData.stage_id = this.stageData.id;
          formData.main_content = this.datas.main_content
            ? this.datas.main_content
            : "";
          formData.curr_moth_plan = this.datas.curr_moth_plan;
          this.saveForm(formData);
          this.cancel();
        } else {
          return false;
        }
      });
    },
    validWeek(rule, value, callback, data) {
      let curIndex = data.findIndex(item => item.propName === rule.field);
      // console.log(data[curIndex].content.length,curIndex,rule.field);
      if (data[curIndex].content && data[curIndex].content.trim().length > 0) {
        return true;
      } else {
        callback(new Error(`请填写内容`));
        return;
      }
      callback();
    },
    isEmpty(value) {
      if (!value || value.length < 1) {
        return true;
      }
      return false;
    },
    validate(id, prop, value, des) {
      if (this.isEmpty(value)) {
        return {
          success: false,
          message: `请填写${des}`
        };
      }
      return { success: true };
    },
    getRules() {
      return {
        project_no: [
          {
            validator: (rule, value, callback) => {
              const result = this.validate(
                this.datas.project_no,
                "project_no",
                this.datas.project_no,
                "项目编号"
              );
              if (!result.success) {
                callback(new Error(result.message));
                return;
              }
              callback();
            },
            trigger: ["blur", "change"]
          }
        ],
        project_id: [
          {
            validator: (rule, value, callback) => {
              const result = this.validate(
                this.datas.project_id,
                "project_id",
                this.datas.project_id,
                "项目名称"
              );
              if (!result.success) {
                callback(new Error(result.message));
                return;
              }
              callback();
            },
            trigger: ["blur", "change"]
          }
        ]
        // project_desc: [
        //   {
        //     validator: (rule, value, callback) => {
        //       const result = this.validate(
        //         this.datas.project_desc,
        //         "project_desc",
        //         this.datas.project_desc,
        //         "项目概述"
        //       );
        //       if (!result.success) {
        //         callback(new Error(result.message));
        //         return;
        //       }
        //       callback();
        //     },
        //     trigger: ["blur", "change"]
        //   }
        // ]
        // class_name: [
        //   {
        //     validator: (rule, value, callback) => {
        //       const result = this.validate(
        //         this.datas.class_name,
        //         "class_name",
        //         this.datas.class_name,
        //         "项目类别"
        //       );
        //       if (!result.success) {
        //         callback(new Error(result.message));
        //         return;
        //       }
        //       callback();
        //     },
        //     trigger: ["blur", "change"]
        //   }
        // ]
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.edit-form {
  height: 66vh;
  overflow-y: auto;
  overflow-x: hidden;
}
.things-item > span {
  cursor: pointer;
  padding-right: 20px;
}
</style>>